import Cookies from "js-cookie";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";

export interface DataInfo<T> {
  /**用户 id */
  id?: string;
  /** json web token id */
  jti: string;
  /** token */
  accessToken: string;
  /** `accessToken`的过期时间（时间戳） */
  expires: T;
  /** 用于调用刷新accessToken的接口时所需的token */
  refreshToken: string;
  /** 头像 */
  avatar?: string;
  /** 用户名 */
  username?: string;
  /** 昵称 */
  nickname?: string;
  /** 当前登录用户的角色 */
  roles?: Array<string>;
  /** 当前登录用户的按钮级别权限 */
  permissions?: Array<string>;
  /** 部门ids */
  deptIds?: string[];
}

export interface AuthorizationCookiesType<T> {
  /** 登录的token */
  accessToken: string;
  /** 刷新token */
  refreshToken: string;
  /** 过期时间 */
  expires: T;
  /** json web token id */
  jti: string;
}

export const userKey = "user-info";

/** 顶级角色 code */
export const ROOTRoleCode = ["ROOT"];

/** 判断是否为顶级角色 */
export function isROOTRole(roles: Array<string>): boolean {
  if (!roles || roles.length === 0) return false;
  return roles.some(role => ROOTRoleCode.includes(role));
}

export const AuthorizedKeyPrefix = "authorized_";

/**
 * 通过`multiple-tabs`是否在`cookie`中，判断用户是否已经登录系统，
 * 从而支持多标签页打开已经登录的系统后无需再登录。
 * 浏览器完全关闭后`multiple-tabs`将自动从`cookie`中销毁，
 * 再次打开浏览器需要重新登录系统
 * */
export const multipleTabsKey = "multiple-tabs";

/** 获取`token` */
export function getToken(
  authorizedData = {
    jti: "",
    accessToken: "",
    expires: 0,
    refreshToken: ""
  }
): DataInfo<number> {
  Object.keys(authorizedData).forEach(key => {
    authorizedData[key] = Cookies.get(AuthorizedKeyPrefix + key);
  });
  const storageLocalData = storageLocal().getItem(userKey) as any;
  return { ...authorizedData, ...storageLocalData };
}

function setAuthorizedCookies(
  authorizedData: AuthorizationCookiesType<number>
) {
  Object.entries(authorizedData).forEach(([key, value]) => {
    authorizedData.expires > 0
      ? Cookies.set(AuthorizedKeyPrefix + key, value, {
          expires: (authorizedData.expires - Date.now()) / 86400000
        })
      : Cookies.set(AuthorizedKeyPrefix + key, value);
  });
}

function removeAuthorizedCookies(
  authorizedData = {
    jti: "",
    accessToken: "",
    expires: 0,
    refreshToken: ""
  }
) {
  Object.keys(authorizedData).forEach(key => {
    Cookies.remove(AuthorizedKeyPrefix + key);
  });
}

/**
 * 补充信息
 * @param param0 token 信息
 */
export function updateTokenInfo({
  id,
  avatar,
  username,
  nickname,
  roles,
  permissions,
  deptIds
}) {
  useUserStoreHook().SET_ID(id);
  useUserStoreHook().SET_AVATAR(avatar);
  useUserStoreHook().SET_USERNAME(username);
  useUserStoreHook().SET_NICKNAME(nickname);
  useUserStoreHook().SET_ROLES(roles);
  useUserStoreHook().SET_PERMS(permissions);
  useUserStoreHook().SET_DEPT_IDS(deptIds);
  const cache = storageLocal().getItem(userKey) as object;
  storageLocal().setItem(userKey, {
    ...cache,
    ...{
      id,
      avatar,
      username,
      nickname,
      roles,
      permissions,
      deptIds
    }
  });
}

/**
 * @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
 * 无感刷新：后端返回`accessToken`（访问接口使用的`token`）、`refreshToken`（用于调用刷新`accessToken`的接口时所需的`token`，`refreshToken`的过期时间（比如30天）应大于`accessToken`的过期时间（比如2小时））、`expires`（`accessToken`的过期时间）
 * 将`accessToken`、`expires`、`refreshToken`这三条信息放在key值为authorized-token的cookie里（过期自动销毁）
 * 将`avatar`、`username`、`nickname`、`roles`、`permissions`、`refreshToken`、`expires`这七条信息放在key值为`user-info`的localStorage里（利用`multipleTabsKey`当浏览器完全关闭后自动销毁）
 */
export function setToken(data: DataInfo<Date>) {
  let expires = 0;
  const { accessToken, refreshToken, jti } = data;
  const { isRemembered, loginDay } = useUserStoreHook();
  expires = new Date(data.expires).getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
  setAuthorizedCookies({
    jti,
    accessToken,
    expires,
    refreshToken
  });

  Cookies.set(
    multipleTabsKey,
    "true",
    isRemembered
      ? {
          expires: loginDay
        }
      : {}
  );

  function setUserKey({
    avatar,
    username,
    nickname,
    roles,
    permissions,
    deptIds
  }) {
    useUserStoreHook().SET_AVATAR(avatar);
    useUserStoreHook().SET_USERNAME(username);
    useUserStoreHook().SET_NICKNAME(nickname);
    useUserStoreHook().SET_ROLES(roles);
    useUserStoreHook().SET_PERMS(permissions);
    useUserStoreHook().SET_DEPT_IDS(deptIds);
    storageLocal().setItem(userKey, {
      refreshToken,
      expires,
      avatar,
      username,
      nickname,
      roles,
      permissions,
      deptIds
    });
  }

  if (data.username && data.roles) {
    const { username, roles } = data;
    setUserKey({
      avatar: data?.avatar ?? "",
      username,
      nickname: data?.nickname ?? "",
      roles,
      permissions: data?.permissions ?? [],
      deptIds: data?.deptIds ?? []
    });
  } else {
    const avatar =
      storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? "";
    const username =
      storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "";
    const nickname =
      storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? "";
    const roles =
      storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
    const permissions =
      storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [];
    const deptIds =
      storageLocal().getItem<DataInfo<number>>(userKey)?.deptIds ?? [];
    setUserKey({
      avatar,
      username,
      nickname,
      roles,
      permissions,
      deptIds
    });
  }
}

/** 删除`token`以及key值为`user-info`的localStorage信息 */
export function removeToken() {
  removeAuthorizedCookies();
  Cookies.remove(multipleTabsKey);
  storageLocal().removeItem(userKey);
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};

/** 是否有按钮级别的权限（根据登录接口返回的`permissions`字段进行判断）*/
export const hasPerms = (value: string | Array<string>): boolean => {
  if (!value) return false;
  const allPerms = "*:*:*";
  const { permissions } = useUserStoreHook();
  if (!permissions) return false;
  if (permissions.length === 1 && permissions[0] === allPerms) return true;
  const isAuths = isString(value)
    ? permissions.includes(value)
    : isIncludeAllChildren(value, permissions);
  return isAuths ? true : false;
};
